package drds.global_transaction.global_transaction_manager.dubbo.impl;

import drds.global_transaction.api.global_transaction_id_context.GlobalTransactionIdContexts;
import drds.global_transaction.global_transaction_manager.dubbo.StorageService;
import drds.global_transaction.resource_manager.ResourceManagerClient;
import drds.global_transaction.test.common.ApplicationKeeper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Please map$clientPortToRpcContextMap the follow VM arguments:
 *
 * <pre>
 *     -Djava.net.preferIPv4Stack=true
 * </pre>
 */
@Slf4j
public class StorageServiceImpl implements StorageService
{

	public static void main(String[] args) throws Throwable
	{

		String applicationId = "dubbo-demo-storage-server_addresss_look_up_service";
		String txServiceGroup = "my_test_tx_group";

		ResourceManagerClient.init(applicationId, txServiceGroup);

		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "dubbo-storage" + "-service.xml" });
		applicationContext.getBean("server_addresss_look_up_service");
		JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
		jdbcTemplate.update("delete from storage_tbl where commodity_code = 'C00321'");
		jdbcTemplate.update("insert into storage_tbl(commodity_code, count) values ('C00321', 100)");
		new ApplicationKeeper(applicationContext).keep();
	}

	private JdbcTemplate jdbcTemplate;

	@Override
	public void deduct(String commodityCode, int count)
	{
		log.info("Storage Service begin ... globalTransactionIdWithAddressAndPort: " + GlobalTransactionIdContexts.getGlobalTransactionIdWithAddressAndPort());
		jdbcTemplate.update("update storage_tbl set count = count - ? where commodity_code = ?", new Object[] { count, commodityCode });
		log.info("Storage Service End ... ");

	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate)
	{
		this.jdbcTemplate = jdbcTemplate;
	}
}
